//
//  LoginViewController.m
//  jungoo
//
//  Created by TrungDQ on 7/24/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "User.h"
#import "Request.h"
#import "AppDelegate.h"
#import "HomeViewController.h"
#import "CreateAccountViewController.h"

@implementation LoginViewController

@synthesize txtEmail;
@synthesize txtPass;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"user"] == nil) {    
        txtEmail.text = @""; //@"ios01@x.com";
        txtPass.text = @"";//@"111111";
    }
    else {
        txtEmail.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"user"];
        txtPass.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
    }
    
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg.png"]]];
    [btnLogin setBackgroundImage:[UIImage imageNamed:@"btn_bg_normal.png.png"]  forState:UIControlStateNormal];
    [btnLogin setTitle:@"Login" forState:UIControlStateNormal];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{    
    return NO;
}

#pragma mark ---Actions---

- (IBAction)loginFB:(id)sender
{
    
    NSArray *permissions = [[NSArray alloc] initWithObjects:
                            @"user_birthday", 
                            @"user_hometown",
                            @"user_photos",
                            @"friends_photos",
                            @"email",
                            nil];
    
    
    AppDelegate *delegate = [AppDelegate shareDelegate];
    if (![[delegate facebook] isSessionValid]) {
        [[delegate facebook] authorize:permissions];
        
    } else {
        [delegate gotoHome];
        NSLog(@"already logged in");
        //already logged in
    }
}

- (void)changeUser
{
    [[AppDelegate shareDelegate] changeUser];
}
-(IBAction) buttonLogin
{
    [self changeUser];
	if([self.txtEmail.text length]==0)
	{
		UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@"Please enter email" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
		[alert show];
		[self.txtEmail becomeFirstResponder];
		return;
	}
	if([self.txtPass.text length]==0)
	{
		UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@"Please enter password" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
		[alert show];
		[self.txtPass becomeFirstResponder];
		return;
	}
	if([self.txtEmail isFirstResponder])
	{
		[self.txtEmail resignFirstResponder];
	}
	if([self.txtPass isFirstResponder])
	{
		[self.txtPass resignFirstResponder];
	}
    
    [JGoUtility showProgressInView:self.view 
                            target:self title:@"Logging In..." selector:@selector(delayLogin:)];
}

- (IBAction)registerAccount:(id)sender
{
    CreateAccountViewController * caVC = [[[CreateAccountViewController alloc] initWithNibName:@"CreateAccountViewController"
                                                                                        bundle:nil] autorelease];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:caVC];
    navController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:navController animated:YES];
}

#pragma Touch

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
	[txtEmail resignFirstResponder];
	[txtPass resignFirstResponder];
	[super touchesBegan:touches withEvent:event];
}

#pragma mark - TextField Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Delay Method

- (void)delayLogin:(MBProgressHUD*)progress
{
    NSError *error = nil;
    NSDictionary *userInfo = nil;
    
    userInfo = [JGoAPI loginWithEmail:txtEmail.text 
                        andPassword:txtPass.text error:&error];
    
    if (error) {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    else {
        LOG(@"%@", [userInfo description]);
        
        [JGoAPI setLocationWithUserId:[userInfo objectForKey:@"user_id"] 
                                                         lat:[JGoUtility sharedLatitude] 
                                                         lon:[JGoUtility sharedLongitude] 
                                                       error:nil];
        
        NSString *modules = [userInfo objectForKey:@"modules"];
        NSString *dobString = [userInfo objectForKey:@"dob"];  
        NSDate *dob = [JGoUtility dateFromString1:dobString];
        
        [userInfo setValue:dob forKey:@"dob"];
        
        if ([modules length]) {
            NSArray *arrayModule = [modules componentsSeparatedByString:@";"];
            [userInfo setValue:arrayModule forKey:@"modules"];
        }
        else {
            [userInfo setValue:nil forKey:@"modules"];
        }    
        
        [JGoUtility copySharedCreateAccount:userInfo];
        HomeViewController *homeView = [[[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil] autorelease];        
        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:homeView];  
        navController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentModalViewController:navController animated:YES]; 
        
        [[NSUserDefaults standardUserDefaults] setValue:txtEmail.text forKey:@"user"];
        [[NSUserDefaults standardUserDefaults] setValue:txtPass.text forKey:@"password"];
    }
    
    [progress hide:YES];
}

@end
